import java.util.InputMismatchException;
import java.util.Scanner;

public class EnhancedProductCalculator {
    // 私有成员变量封装数据
    private int amount;
    private float price;

    // 构造方法初始化
    public EnhancedProductCalculator() {
        this.amount = 0;
        this.price = 0.0f;
    }

    // 输入验证方法（封装输入逻辑）
    private float getValidatedInput(Scanner scanner, String prompt, String type) {
        while(true) {
            try {
                System.out.print(prompt);
                return type.equals("int") ? scanner.nextInt() : scanner.nextFloat();
            } catch(InputMismatchException e) {
                System.out.println("输入格式错误，请重新输入数字！");
                scanner.nextLine(); // 清除错误输入
            }
        }
    }

    // 业务逻辑方法
    public void calculate() {
        Scanner scanner = new Scanner(System.in);

        try {
            // 带验证的输入获取
            this.amount = (int) getValidatedInput(scanner, "请输入产品数量: ", "int");
            this.price = getValidatedInput(scanner, "请输入产品单价: ", "float");

            // 数值有效性检查
            if(amount <= 0 || price <= 0) {
                String errorMsg = String.format("非法参数值！amount=%.2f, price=%.2f", amount, price);
                System.err.println(errorMsg); // 打印具体错误值
                throw new IllegalArgumentException("数值必须大于零");
            }

            // 计算结果
            float total = calculateTotal();

            // 格式化输出
            printResult(total);

        } finally {
            scanner.close(); // 确保资源释放
        }
    }

    // 计算逻辑单独封装
    private float calculateTotal() {
        return amount * price;
    }

    // 输出格式化封装
    private void printResult(float sum) {
        System.out.println("\n======= 产品明细 =======");
        System.out.printf("产品数量 (amount): %d 件%n", amount);
        System.out.printf("产品单价 (price): ¥%.2f%n", price);
        System.out.printf("总价值 (sum): ¥%.2f%n", sum);
    }

    public static void main(String[] args) {
        EnhancedProductCalculator calculator = new EnhancedProductCalculator();
        calculator.calculate();
    }
}
